from django.forms import models
from django.db.models import Model
from django.forms.fields import CallableChoiceIterator

from oracle.base.tools import get_random_string


def form_object_to_json(data):
    """
    将form类型处理成为json能格式化的数据
    :param data: 字典类型，data["form"]存储的为form类型，为处理的数据
    :return:
    """
    form = dict()
    index = 0
    for item in data["form"]:
        form[index] = {
            "name": item.name,
            "help_text": item.field.help_text,
            "initial": item.field.initial,
            "label": item.field.label,
            "required": item.field.required,
            "error": item.errors,
        }
        if hasattr(item.field, "choices"):
            # 外键或M2M情况，查询到的是queryset数据，需要进行处理
            if isinstance(item.field.choices, models.ModelChoiceIterator):
                form[index]["choices"] = [(i.key, str(i),) for i in item.field.choices.queryset]
                if not item.field.initial:
                    form[index]["choices"].insert(0, (
                        item.field.choices.field.empty_values[0], item.field.choices.field.empty_label))
            elif isinstance(item.field.choices, CallableChoiceIterator):
                form[index]["choices"] = [choice for choice in item.field.choices]
            else:
                form[index]["choices"] = item.field.choices
        # 新建时instance没有意义，只修改时获取
        # TODO 极度疲惫的时候完成，没有考虑最优解
        if data.get("operation") == "change":
            form[index]["instance"] = getattr(data["form"].instance, item.name)
            if isinstance(form[index]["instance"], list):
                form[index]["instance"] = [str(item) for item in form[index]["instance"]]
            elif isinstance(form[index]["instance"], Model):
                if hasattr(item.field, "choices"):
                    form[index]["instance"] = form[index]["instance"].key
                else:
                    form[index]["instance"] = str(form[index]["instance"])
        index += 1
    data["form"] = form


def formset_object_to_json(data):
    """
    将form类型处理成为json能格式化的数据
    :param data: 字典类型，data["form"]存储的为form类型，为处理的数据
    :return:
    """
    # formset格式化成为json的数据
    formset_json_data = list()
    for form in data["formset"]:
        # 每个form格式化成为json的数据
        form_json_data = dict()
        index = 0
        for item in form:
            form_json_data[index] = {
                "name": item.name,
                "help_text": item.field.help_text,
                "initial": item.field.initial,
                "label": item.field.label,
                "required": item.field.required,
                "error": item.errors,
            }
            if item.name in form.initial:
                form_json_data[index]["initial"] = form.initial.get(item.name)
            if hasattr(item.field, "choices"):
                # 外键或M2M情况，查询到的是queryset数据，需要进行处理
                if isinstance(item.field.choices, models.ModelChoiceIterator):
                    form_json_data[index]["choices"] = [(i.key, str(i),) for i in item.field.choices.queryset]
                    if not item.field.initial:
                        form_json_data[index]["choices"].insert(0, (
                            item.field.choices.field.empty_values[0], item.field.choices.field.empty_label))
                # 自定了choices的获取方法，比如通过model获取queryset等，需要通过执行循环获取元素
                elif isinstance(item.field.choices, CallableChoiceIterator):
                    form_json_data[index]["choices"] = [choice for choice in item.field.choices]
                # 普通定义只需直接取即可
                else:
                    form_json_data[index]["choices"] = item.field.choices
            # 新建时instance没有意义，只修改时获取
            # TODO 极度疲惫的时候完成，没有考虑最优解
            if data.get("operation") == "change":
                form_json_data[index]["instance"] = getattr(form.instance, item.name)
                if isinstance(form_json_data[index]["instance"], list):
                    form_json_data[index]["instance"] = [str(item) for item in form_json_data[index]["instance"]]
                elif isinstance(form_json_data[index]["instance"], Model):
                    if hasattr(item.field, "choices"):
                        form_json_data[index]["instance"] = form_json_data[index]["instance"].key
                    else:
                        form_json_data[index]["instance"] = str(form_json_data[index]["instance"])
            index += 1
        formset_json_data.append(form_json_data)
    data["formset"] = formset_json_data


def get_only_key(model_object, key=None):
    """
    获取唯一键值
    :param model_object: model实例
    :param key: 传入自定义key值
    :return:
    """
    if not key:
        key = get_random_string(24)
    # TODO 性能问题
    # 确保获取的key唯一
    while True:
        if not model_object.objects.filter(key=key).exists():
            break
        key = get_random_string(24)
    return key
